package com.frxuexi.cart.view

import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.cart.viewmodel.CartViewModel
import com.frxuexi.cart.R
import com.frxuexi.cart.adapter.AddressAdapter
import com.frxuexi.cart.databinding.ActivityAddressListBinding
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.lib_base.utils.ArouterManager
import dagger.hilt.android.AndroidEntryPoint

@Route(path = "/cart/AddressListActivity")
@AndroidEntryPoint
class AddressListActivity : BaseActivity<ActivityAddressListBinding, CartViewModel>() {
    val addressAdapter by lazy { AddressAdapter() }
    override fun initData() {
        vm.addressData.observe(this){
            addressAdapter.apply {
//                加载列表
                data.clear()
                addData(it.list)
                notifyDataSetChanged()
            }
        }

        vm.deleteAddressData.observe(this){
            ToastUtils.showLong("删除成功")
            vm.getAddress()
        }

    }

    override fun initView() {
        binding.addRv.apply {
            adapter=addressAdapter
            layoutManager=LinearLayoutManager(this@AddressListActivity)
        }


        binding.addAdd.setOnClickListener {
            ArouterManager.nav(this,"/cart/AddreddEditActivity")
        }

        addressAdapter.setOnItemClickListener { adapter, view, position ->
//            点击地址item，把地址信息传回 订单确认页面
            ARouter.getInstance().build("/cart/OrderConfirmActivity").withSerializable("address",addressAdapter.data.get(position)).navigation()
        }

        addressAdapter.addChildClickViewIds(R.id.con_edit,R.id.con_delete)
        addressAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = addressAdapter.data.get(position)
            when(view.id){
                R.id.con_edit->{
                    ArouterManager.nav(this,"/cart/AddreddEditActivity",item.id)
                }
                R.id.con_delete->{
//                    删除
                    vm.deleteAddress(mapOf("id" to item.id))
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
//        页面进来就加载地址列表
        vm.getAddress()
    }

}